package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.entity.GouwucheEntity;
import com.keyinong.caizhengting.entity.ShangpinEntity;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.view.widget.RatingBarView;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/4/3
 */
public class GoodsDetailActivity extends Activity {

    private static final String TAG = "GoodsDetailActivity";

    @BindView(R.id.rb_rank)
    RatingBarView mRbRank;
    @BindView(R.id.iv_goods)
    ImageView mIvGoods;
    @BindView(R.id.tv_goods_name)
    TextView mTvName;
    @BindView(R.id.tv_goods_limit)
    TextView mTvLimit;
    @BindView(R.id.tv_goods_price)
    TextView mTvGoodsPrice;
    @BindView(R.id.tv_goods_number)
    TextView mTvGoodsNum;
    @BindView(R.id.iv_goods_add)
    ImageView mIvAdd;
    @BindView(R.id.tv_total_num)
    TextView mTvTotalNum;
    @BindView(R.id.tv_total_price)
    TextView mTvTotalPrice;
    @BindView(R.id.tv_goods_intro)
    TextView mTvGoodsIntro;

    private ShangpinEntity mGoodsEntity;

    private HttpTools mHttpTools;

    private int mGoodsNum = 0;

    private ArrayList<GouwucheEntity> mShoppingCart;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_goods_detail);
        ButterKnife.bind(this);

        Intent intent = getIntent();

        if (null != intent) {

            Bundle bundle = getIntent().getExtras();
            if (null != bundle) {
                mGoodsEntity = (ShangpinEntity) bundle.getSerializable("GOODS_DETAIL");
                mGoodsNum = bundle.getInt("GOODS_NUM");

                Log.e(TAG, String.valueOf(mGoodsEntity.getId()) + ":" + String.valueOf(mGoodsNum));
            }
        }

        if (null != mGoodsEntity) {
            Glide.with(this)
                    .load(mGoodsEntity.getImage())
                    .into(mIvGoods);
            mRbRank.setStar(5);
            mTvName.setText(mGoodsEntity.getName());
            mTvLimit.setText(String.format("剩余%s", mGoodsEntity.getStock()));
            mTvGoodsPrice.setText(mGoodsEntity.getPrice());
            mTvGoodsIntro.setText(mGoodsEntity.getContent());
            mTvGoodsNum.setText(String.valueOf(mGoodsNum));
        }

        initShoppingCart();
    }

    private void initShoppingCart() {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        mShoppingCart = new ArrayList<>();

        SharedPreferences sp = getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        HttpTools httptools = new HttpTools(this);

        httptools.getShoppingCat(token, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    boolean code = response.getBoolean("code");
                    String msg = response.getString("msg");
                    if (code) {
                        JSONObject object = response.getJSONObject("data");
                        String geshu = object.getString("amount");
                        String total = object.getString("total");
                        JSONArray array = object.getJSONArray("shoppingcarts");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject data = array.getJSONObject(i);
                            String id = data.getString("id");
                            String productid = data.getString("productid");
                            String name = data.getString("name");
                            String content = data.getString("content");
                            String price = data.getString("price");
                            int type = data.getInt("type");
                            String shelve = data.getString("shelve");
                            String stock = data.getString("stock");
                            String perlim = data.getString("perlim");
                            String amount = data.getString("amount");
                            String buyamount = data.getString("buyamount");
                            mShoppingCart.add(new GouwucheEntity(id, productid, name, content, price, amount, shelve, stock, perlim, buyamount, type));
                        }
                        mTvTotalNum.setText(geshu);
                        mTvTotalPrice.setText(total);
                    } else {
                        Toast.makeText(GoodsDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
            }
        });
    }

    @OnClick(R.id.ib_back)
    public void onViewClicked() {
        onBackPressed();
    }

    @OnClick({R.id.ib_back, R.id.iv_goods_add, R.id.iv_goods_minus, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                onBackPressed();
                break;
            case R.id.iv_goods_add:
                mGoodsNum += 1;
                addGoods();
                break;
            case R.id.iv_goods_minus:
                mGoodsNum -= 1;
                if (mGoodsNum < 0) {
                    Toast.makeText(this, "数量已经为0", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mGoodsNum == 0) {
                    deleteGoods();
                    return;
                }
                minusGoods();
                break;
            case R.id.btn_submit:
                Intent intent = new Intent();
                intent.setClass(GoodsDetailActivity.this, FanqiedingcanActivity.class);
                intent.putExtra("code", "1");
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    private void addGoods() {
        if (!NetWorkUtil.isNetwork(this)) {
            Toast.makeText(this, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mTvGoodsNum.getText().toString())) {
            mTvGoodsNum.setText(String.format("%s", 0));
        }
        SharedPreferences sp = this.getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (mHttpTools == null) {
            mHttpTools = new HttpTools(this);
        }

        mHttpTools.addgoodscat(token, mGoodsEntity.getId(), String.valueOf(mGoodsNum), new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    Log.i("zq", response.toString());
                    boolean code = response.getBoolean("code");
                    String msg = response.getString("msg");
                    if (code) {
                        JSONObject data = response.getJSONObject("data");
                        String amount = data.getString("amount");
                        String total = data.getString("total");
                        mIvAdd.setEnabled(true);

                        mTvGoodsNum.setText(String.valueOf(mGoodsNum));

                        mTvTotalNum.setText(amount);
                        mTvTotalPrice.setText(total);

                        setMsg("jia1", amount, 0);
                        setMsg("zongjia1", total, 0);


                        setMsg1("jia1", amount, 0);
                        setMsg1("zongjia1", total, 0);
                    } else {
                        mIvAdd.setEnabled(true);
                        Toast.makeText(GoodsDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Log.e(TAG, errorResponse.toString());
            }
        });
    }

    private void minusGoods() {
        if (!NetWorkUtil.isNetwork(this)) {
            Toast.makeText(this, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mTvGoodsNum.getText().toString())) {
            mTvGoodsNum.setText(String.format("%s", 0));
            mGoodsNum = 0;
        }

        SharedPreferences sp = this.getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        if (mHttpTools == null) {
            mHttpTools = new HttpTools(this);
        }

        mHttpTools.addgoodscat(token, mGoodsEntity.getId(), String.valueOf(mGoodsNum),
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            Log.i("info", response.toString());
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            int goodsNum = Integer.parseInt(mTvGoodsNum.getText().toString());
                            if (code) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");
                                int goodsNum2 = Integer.parseInt(mTvGoodsNum.getText().toString());

                                mTvGoodsNum.setText(String.valueOf(mGoodsNum));

                                mTvTotalNum.setText(amount);
                                mTvTotalPrice.setText(total);

                                int lim = Integer.parseInt(mGoodsEntity.getStock());

                                setMsg("jian1", amount, 0);
                                setMsg("zongjia1", total, 0);

                                setMsg1("jian1", amount, 0);
                                setMsg1("zongjia1", total, 0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    private void deleteGoods() {
        if (!NetWorkUtil.isNetwork(this)) {
            Toast.makeText(this, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = this.getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        if (mHttpTools == null) {
            mHttpTools = new HttpTools(this);
        }
        mHttpTools.remove(token, mGoodsEntity.getId(), new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("zq", "删除------------" + response.toString());
                try {
                    boolean code = response.getBoolean("code");
                    String msg = response.getString("msg");
                    if (code) {
                        JSONObject data = response.getJSONObject("data");
                        String amount = data.getString("amount");
                        String total = data.getString("total");

                        mTvGoodsNum.setText(String.valueOf(0));
                        mTvTotalNum.setText(amount);
                        mTvTotalPrice.setText(total);

                        setMsg("qingchu1", amount, 0);
                        setMsg("zongjia1", total, 0);


                        setMsg1("qingchu1", amount, 0);
                        setMsg1("zongjia1", total, 0);
                    } else {
                        Toast.makeText(GoodsDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    private void setMsg(String sopt, String str, int index) {
        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("sopt1", sopt);
        bundle.putString("str1", str);
        bundle.putInt("index1", index);
        message.obj = bundle;
        GoodsTwoSortActivity.myhanler.sendMessage(message);
    }

    private void setMsg1(String sopt, String str, int index) {
        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("sopt1", sopt);
        bundle.putString("str1", str);
        bundle.putInt("index1", index);
        message.obj = bundle;
        FanqiedingcanActivity.myhanler.sendMessage(message);
    }
}
